import { ShellUtil } from "./ShellUtil";
import { Main } from "../Main";
import { DirUtil } from "./DirUtil";
import * as fs from "fs"
import { parseString } from "xml2js";
import { FileIoUtil } from "./FileIOUtil";
import { normalize } from "path";


type ExportMap = {
    ani:{[key:string]:true}
    pic:{[key:string]:true}
}
/**
 * 美术下ne到程序下的cocosstudio的同步工具
 * @author 赵占涛
 */
export class NeArt2CocosStudioUtil {
    /**
     * 放到cocosstudio下
     * @param filePath ans的文件路径或文件夹路径
     */
    static export(filePath:string, cb:()=>void) {
        this.getInfo(filePath, (exportMap:ExportMap)=>{
            console.log("本次同步的文件有", exportMap);
            this.exportAni(Object.keys(exportMap.ani), ()=>{
                this.exportPic(Object.keys(exportMap.pic), ()=>{
                    console.log("export to cocosstudio ok");
                    cb();
                });
            });
        });
    }
    /** 导出ani */
    private static exportAni(aniArr:string[], cb:()=>void){
        let count = 0;
        for (let i = 0; i < aniArr.length; i++) {
            const ani = aniArr[i];
            ShellUtil.exec(`
cp -f ${Main.projPath}public/art/cocosstudio/cocosstudio/neAni/ani/${ani} ${Main.codePath}Resources/cocosstudio/cocosstudio/neAni/ani/${ani} || exit 1
            `, ()=>{
                count++;
                if (count == aniArr.length) {
                    cb();
                }
            });
        }
    }
    /** 导出图片 */
    private static exportPic(picArr:string[], cb:()=>void){
        let count = 0;
        for (let i = 0; i < picArr.length; i++) {
            const pic = picArr[i];
            ShellUtil.exec(`
rsync -avz --delete ${pic}/ ${Main.codePath}Resources/cocosstudio/cocosstudio/ccs/neAni/${pic.substr(pic.lastIndexOf("/") + 1)}/ || exit 1
            `, ()=>{
                count++;
                if (count == picArr.length) {
                    cb();
                }
            });
        }
    }
    /** 获取需要导出的信息 */
    private static getInfo(filePath: string, cb: (exportMap:ExportMap) => void) {
        // 要导出的东西
        let exportMap : ExportMap = {ani:{}, pic:{}};

        if (filePath.endsWith(".ans")) {
            this.getInfoAnsArr(exportMap, [filePath], ()=>{
                cb(exportMap);
            });
        } else {
            let filePaths = DirUtil.getAllFile(filePath);
            for (let i = 0; i < filePaths.length; i++) {
                filePaths[i] = filePath + filePaths[i];
            }
            this.getInfoAnsArr(exportMap, filePaths, ()=>{
                cb(exportMap);
            });
        }
    }
    /** 获取信息 导出一个ans数组 */
    private static getInfoAnsArr(exportMap:ExportMap, filePaths:string[], cb:()=>void) {
        let count = 0;
        for (let i = 0; i < filePaths.length; i++) {
            const file = filePaths[i];
            this.getInfoAnsOne(exportMap, file, ()=>{
                count ++;
                if (count == filePaths.length) {
                    cb();
                }
            })
        }
    }
    /** 获取信息 导出一个ans文件 */
    private static getInfoAnsOne(exportMap:ExportMap, filePath:string, cb:()=>void) {
        FileIoUtil.readFile(filePath, (data)=>{
            parseString(data, (err, result)=>{
                if (!result.NEAFile) {
                    // 不是ans文件
                    cb();
                    return;
                }
                if (result.NEAFile.Textures[0] != '') {
                    for (let i = 0; i < result.NEAFile.Textures[0].Texture.length; i++) {
                        const element = result.NEAFile.Textures[0].Texture[i];
                        
                        let picName = element.$.name;
                        exportMap.pic[
                            normalize(filePath.substring(0, filePath.lastIndexOf("/") + 1) + picName)
                        ] = true;
                    }
                }
                exportMap.ani[filePath.substr(filePath.lastIndexOf("/") + 1).replace(".ans", ".ani")] = true;


                let NESFiles = result.NEAFile.NESFiles;
                console.log(JSON.stringify(NESFiles))
                if (NESFiles.length == 0 || NESFiles[0] == "" || NESFiles[0].NESFile.length == 0) {
                    cb();
                } else {
                    let cbCount = 0;
                    for (let i = 0; i < NESFiles[0].NESFile.length; i++) {
                        console.log("ans for", i);
                        if (NESFiles[i] == '') {
                            cb();
                            return;
                        }
                        let ansFile = NESFiles[0].NESFile[i].$.value;
                        let ansFileAbs = filePath.substring(0, filePath.lastIndexOf("/") + 1) + ansFile; // 文件的绝对路径
                        let oneCb = ()=>{
                            cbCount ++;
                            if (cbCount == NESFiles[0].NESFile.length) {
                                cb();
                            }
                        };
                        if (ansFileAbs.endsWith(".ans")) {
                            this.getInfoAnsOne(exportMap, ansFileAbs, oneCb);
                        } else {
                            oneCb();
                        }
                    }
                }
            });
        });
    }
}